package com.landleaf.smarthome.net.http;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ihsanbal.logging.Level;
import com.ihsanbal.logging.LoggingInterceptor;
import com.landleaf.smarthome.App;
import com.landleaf.smarthome.BuildConfig;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.internal.platform.Platform;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by 海航
 * 2019/8/13
 * 功能描述:
 */
public class ApiFactory {

    private static volatile OkHttpClient client;
    private static final String RETROFIT_CACHE_FILE_NAME = "retrofit";
    private volatile static NetApi testApi;


    private static OkHttpClient getClient() {
        if (client == null) {
            synchronized (ApiFactory.class) {
                if (client == null) {
                    OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
                            .cache(new Cache(new File(App.getInstance().getCacheDir(), RETROFIT_CACHE_FILE_NAME), 10 * 1024 * 1024))
                            .connectTimeout(30, TimeUnit.SECONDS)
                            .readTimeout(30, TimeUnit.SECONDS)
                            .addInterceptor(new NetInterceptor())
                            .retryOnConnectionFailure(true);

                    if (BuildConfig.DEBUG) {
                        //打印网络请求日志
                        LoggingInterceptor httpLoggingInterceptor = new LoggingInterceptor.Builder().
                                loggable(true)
                                .setLevel(Level.BASIC)
                                .log(Platform.INFO)
                                .request("Request")
                                .response("Response")
                                .build();
                        clientBuilder.addInterceptor(httpLoggingInterceptor);
                    }
                    client = clientBuilder.build();
                }
            }
        }
        return client;
    }
    public static NetApi getNetApi() {
        if (testApi == null) {
            synchronized (ApiFactory.class) {
                if (testApi == null) {
                    testApi = getRetrofitBuilder()
                            .baseUrl(UrlConsts.BASE_URL)
                            .build().create(NetApi.class);
                }
            }
        }
        return testApi;
    }
    public static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    private static Retrofit.Builder getRetrofitBuilder() {
        return new Retrofit.Builder()
                .client(getClient())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create());
    }

    private ApiFactory() {
    }

}

